package com.yixuan.mt.common.utitls;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yixuan.mt.common.cache.PoliciesCache;
import com.yixuan.mt.common.entity.Policy;
import com.yixuan.mt.common.service.IdentityService;
import com.yixuan.mt.common.service.PoliciesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class PoliciesCacheUtils {

    @Autowired
    private PoliciesCache policiesCache;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private PoliciesService policiesService;

    public void addUserPolicyCache(Integer userId) throws JsonProcessingException {
        List<Policy> policies = identityService.getUserPoliciesList(userId);
        // 获取策略内容
        List<String> policyContentList = new ArrayList<>();
        for (Policy policy : policies) {
            policyContentList.add(policiesService.getPolicyDetail(policy.getId()));
            policiesCache.addPolicyUserMapping(policy.getId(), userId);
        }
        policiesCache.addPolicyContent(userId, policyContentList);
    }

    public void updateUserPolicyCache(Integer userId) throws JsonProcessingException {
        List<Policy> policies = identityService.getUserPoliciesList(userId);
        // 获取策略内容
        List<String> policyContentList = new ArrayList<>();
        for (Policy policy : policies) {
            policyContentList.add(policiesService.getPolicyDetail(policy.getId()));
        }
        policiesCache.updatePolicyContent(userId, policyContentList);
    }

    public void removePolicyCache(Integer policyId) throws JsonProcessingException {
        List<Integer> userIdList = policiesCache.getUserIdList(policyId);
        for (Integer userId : userIdList) {
            updateUserPolicyCache(userId);
        }
        policiesCache.removePolicyMapping(policyId);
    }

    public void updatePolicyCache(Integer policyId) throws JsonProcessingException {
        List<Integer> userIdList = policiesCache.getUserIdList(policyId);
        if (userIdList == null) return;
        for (Integer userId : userIdList) {
            updateUserPolicyCache(userId);
        }
    }
}
